package com.qiantu.phone.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.lifecycle.LifecycleOwner;
import androidx.viewpager.widget.ViewPager;

import com.heytap.mcssdk.utils.LogUtil;
import com.hjq.base.BaseActivity;
import com.hjq.base.DensityUtils;
import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.db.LLDeviceActionDBManager;
import com.qiantu.api.db.LLDeviceCustomDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.db.LLFloorDBManager;
import com.qiantu.api.db.LLSceneDBManager;
import com.qiantu.api.entity.DeviceBaseConfigInfo;
import com.qiantu.api.entity.DeviceBean;
import com.qiantu.api.entity.DeviceBindingData;
import com.qiantu.api.entity.DeviceCustomKeyBean;
import com.qiantu.api.entity.DeviceState;
import com.qiantu.api.entity.FloorBean;
import com.qiantu.api.entity.PanelBindConfig;
import com.qiantu.api.entity.PanelBindStatusBean;
import com.qiantu.api.entity.SceneBean;
import com.qiantu.api.entity.SwitchBindActionBean;
import com.qiantu.api.entity.SwitchBindBean;
import com.qiantu.api.entity.UniversalDeviceData;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.DeviceInfoParseUtil;
import com.qiantu.phone.R;
import com.qiantu.phone.aop.Log;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.event.DeviceKeyNameChangeEvent;
import com.qiantu.phone.ui.dialog.AreaSelectDialog;
import com.qiantu.phone.ui.fragment.DeviceListFragment;
import com.qiantu.phone.ui.fragment.SceneListFragment;
import com.qiantu.phone.widget.OperateBindView;
import com.qiantu.phone.widget.ViewPagerIndicator;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PanelBingingActivity extends AppActivity {
    private String[] tabs = new String[]{"设备", "场景"};
    private OperateBindView operateBindView;
    private TextView selectArea;
    private  SceneListFragment sceneListFragment;
    private  DeviceListFragment deviceListFragment;
    private int operateType;//1:设备；2：场景；3：灯组
    private String bindSerialNo;
    private int panelIndex;//当bingtype=2时，代表绑定上限
    private String panelSerialNo;
    private String name;
    private int checkCount;
//    点击确定后的操作类型： 0：进行绑定；1：返回绑定参数
    private int operateResultType = 0;
//    绑定类型： 0：拍照绑定；1：弗雷克面板; 2:开关批量绑定
    private int bingingType = 0;
    List<Map> bingingDatas = new ArrayList<>();
    @Log
    public static void start(Context context) {
        Intent intent = new Intent(context, PanelBingingActivity.class);
        if (!(context instanceof Activity)) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }
    private ViewPager viewPager;
    private ViewPagerIndicator tabBar;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_panel_binging;
    }

    @Override
    protected void initView() {
        panelIndex = getIntent().getIntExtra("panelIndex",1);
        panelSerialNo = getIntent().getStringExtra("panelSerialNo");
        operateResultType = getIntent().getIntExtra("operateType",0);
        bingingType = getIntent().getIntExtra("bingingType",0);
        if(bingingType == 2){
            getTitleBar().setRightTitle(R.string.save);
        }

        viewPager = findViewById(R.id.view_pager);
        tabBar = findViewById(R.id.tab_bar);
        initViewPager();

        selectArea = findViewById(R.id.select_area);
        operateBindView = findViewById(R.id.operate_bind_view);
        operateBindView.setNoNextStep(true);
        operateBindView.setShowChildView(bingingType != 1);
        operateBindView.setCallback(new OperateBindView.Callback() {
            @Override
            public void requestInit(String statusKey, String statusValueName, Object statusValue, int bindActionType, int actionType) {
                if(bingingType == 1){
                    PanelBindConfig config = new PanelBindConfig();
                    config.setBindSerialNo(bindSerialNo);
                    config.setPanelSalveSn(panelSerialNo);
                    config.setPanelIndex(panelIndex);
                    config.setDeviceName(name);
                    config.setHouseSerialNo(AppApplication.getInstance().getCurrentHouseSerialNo());
                    if(operateType == 2){
                        config.setBindType(7);
                    }else{
                        config.setBindType(11);
                        List<String> commands = new ArrayList<>();
                        commands.add(statusKey);
                        config.setCommands(commands);
                    }
                    LLHttpManager.panelBind(getAppActivity(), config, new HttpCallback<HttpData<PanelBindConfig>>(getAppActivity()){
                        @Override
                        public void onSucceed(HttpData<PanelBindConfig> result) {
                            super.onSucceed(result);
                            //拿到CoreId后开始轮询等待服务器返回绑定成功 10秒后失败 3秒请求一次
                            operateBindView.startWait10SecondAnimator(result.getData().getSerialNo());
                        }

                        @Override
                        public void onFail(Exception e) {
                            super.onFail(e);
                        }
                    });
                }else{
                    panelQRBinging(statusKey,statusValueName,statusValue,bindActionType,actionType);
                }
            }

            @Override
            public void requestInitQuery(String coreId) {
                if(bingingType == 1){
                    LLHttpManager.checkPanelBindingStatus(getAppActivity(), 1, coreId, new HttpCallback<HttpData<PanelBindStatusBean>>(getAppActivity()){
                        @Override
                        public void onSucceed(HttpData<PanelBindStatusBean> result) {
                            super.onSucceed(result);
                            if (result.getData().status == 1){
                                operateBindView.bindComplete(new OperateBindView.DelayTimeCallBack() {
                                    @Override
                                    public void callback(int time) {
//                                        startActivity_SingleTask(PanelBindConfigActivity.class);
                                    }
                                });
                            }
                        }
                    });
                }else{
                    checkPanelQRBinging(coreId);
                }
            }
        });

        setOnClickListener(selectArea);
    }

    @Override
    public void onRightClick(View view) {
        gotoAutoBinging();
    }

    protected void gotoAutoBinging(){
        if (bingingDatas.isEmpty()){//不能点保存

        }else {
            Intent intent = new Intent(getContext(), PanelQRBingingActivity.class);
            intent.putExtra("deviceSerialNo",panelSerialNo);
            intent.putExtra("bingingDatas", (Serializable) bingingDatas);
            getContext().startActivity(intent);
        }


    }

    protected void editKeyName(){
        DeviceCustomKeyBean mEditKey = new DeviceCustomKeyBean();
        mEditKey.setDeviceSerialNo(panelSerialNo);
        mEditKey.setCustomKeySerialNo("");
        mEditKey.setKeyIndex(panelIndex + "");
        LLHttpManager.saveCustomKeyName((LifecycleOwner) getContext(), mEditKey, name, new HttpCallback<HttpData<List<DeviceCustomKeyBean>>>(this){
            @Override
            public void onSucceed(HttpData<List<DeviceCustomKeyBean>> result) {
                super.onSucceed(result);
                List<DeviceCustomKeyBean> beans = result.getData();
                for(DeviceCustomKeyBean bean : beans){
                    LLDeviceCustomDBManager.getInstance(getContext()).put(bean);
                    EventBus.getDefault().post(new DeviceKeyNameChangeEvent(bean.getKeyIndex(),bean.getKeyName()));
                }
                operateBindView.endWait();
                hideDialog();
                toast("绑定成功");
                finish();
            }

            @Override
            public void onFail(Exception e) {
                hideDialog();
                operateBindView.endWait();
                showFailView();
            }
        });
    }

    private void initViewPager() {
        List<Fragment> fragments = new ArrayList<>();
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return tabs.length;
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return null;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }
        });
        tabBar.setupViewpager(viewPager);
        tabBar.setTitles(tabs);

        sceneListFragment = SceneListFragment.newInstance(SceneListFragment.TYPE_BING_LIST,bingingType);
        sceneListFragment.setActivity(this);
        deviceListFragment = DeviceListFragment.newInstance(this,bingingType);
        fragments.add(deviceListFragment);
        fragments.add(sceneListFragment);
        viewPager.setCurrentItem(0);
    }

    private void panelQRBinging(String statusKey, String statusValueName, Object statusValue, int bindActionType, int actionType){
        Map data = new HashMap();
        data.put("name","按键"+panelIndex);
        data.put("info",name);
        data.put("houseSerialNo", AppApplication.getInstance().getCurrentHouseSerialNo());
        data.put("switchSerialNo",panelSerialNo);
        data.put("switchKeyOpreate",1);
        data.put("switchKeyIndex",panelIndex);
        data.put("bindSerialNo",bindSerialNo);
        data.put("bindType",operateType);
        SwitchBindActionBean bindActionBean = new SwitchBindActionBean();
        if (operateType == 1){
            bindActionBean.setDeviceState(new DeviceState());
            bindActionBean.getDeviceState().setStatus(new DeviceState.StatusDTO(1));
            try {
                Field field = bindActionBean.getDeviceState().getStatus().getClass().getDeclaredField(statusKey);
                field.setAccessible(true);
                field.set(bindActionBean.getDeviceState().getStatus(), (Integer) statusValue);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
            bindActionBean.setDeviceSerialNo(bindSerialNo);
            data.put("actionType",actionType);
            data.put("bindActionType",bindActionType);
            data.put("bindAction",bindActionBean);
        } else if (operateType == 2){
            if(!TextUtils.isEmpty(bindSerialNo)){
                bindActionBean.setSceneSerialNo(bindSerialNo);
            }
            data.put("actionType",0);
            data.put("bindActionType",0);
            data.put("bindAction",bindActionBean);
        }else if (operateType == 3){
            bindActionBean.setDeviceGroupState(new DeviceState());
            bindActionBean.getDeviceGroupState().setStatus(new DeviceState.StatusDTO(1));
            try {
                Field field = bindActionBean.getDeviceGroupState().getStatus().getClass().getDeclaredField(statusKey);
                field.setAccessible(true);
                field.set(bindActionBean.getDeviceGroupState().getStatus(), (Integer) statusValue);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                e.printStackTrace();
            }
            bindActionBean.setDeviceSerialNo(bindSerialNo);
            data.put("actionType",actionType);
            data.put("bindActionType",bindActionType);
            data.put("bindAction",bindActionBean);
        }
        if(bingingType == 2){
            int sameIndex = checkSame(bindSerialNo);
            if(sameIndex != -1){
                data.put("name","按键"+sameIndex);
                data.put("switchKeyIndex",sameIndex);
                bingingDatas.add(sameIndex,data);
                bingingDatas.remove(sameIndex + 1);
            }else{
                Integer index = -1;
                for(Integer i = 0;i < bingingDatas.size();i++){
                    boolean isHave = false;
                    for(Map bingMap : bingingDatas){
                        int switchKeyIndex = Integer.parseInt(bingMap.get("switchKeyIndex").toString());
                        if((i+1) == switchKeyIndex){
                            isHave = true;
                            break;
                        }
                    }
                    if(!isHave){
                        index = i;
                        break;
                    }
                }
                if(index == -1){
                    index = bingingDatas.size()+1;
                    bingingDatas.add(data);
                }else{
                    index = index + 1;
                    bingingDatas.add(index,data);
                }
                data.put("name","按键"+index);
                data.put("switchKeyIndex",index);
                if(operateType == 2){
                    sceneListFragment.setSortData(bindSerialNo,index);
                }else{
                    deviceListFragment.setSortData(bindSerialNo,index);
                }
            }
            operateBindView.setVisibility(View.GONE);
        }else{
            if(operateResultType == 1){
                Intent intent = new Intent();
                intent.putExtra("data", (Serializable) data);
                setResult(RESULT_OK,intent);
                finish();
            }else{
                showDialog();
                LLHttpManager.addQuickBindSwitch(PanelBingingActivity.this, data, new HttpCallback<HttpData<Map>>(PanelBingingActivity.this) {
                    @Override
                    public void onSucceed(HttpData<Map> result) {
                        super.onSucceed(result);
                        if (result.getData() != null && result.getData().get("taskId") != null) {
                            checkCount = 0;
                            //拿到CoreId后开始轮询等待服务器返回绑定成功 10秒后失败 3秒请求一次
                            operateBindView.startWaitWithoutAnimator(result.getData().get("taskId").toString());
                        }else{
                            hideDialog();
                        }
                    }
                    @Override
                    public void onFail(Exception e) {
                        super.onFail(e);
                    }
                });
            }
        }
    }

    private void checkPanelQRBinging(String coreId){
        LLHttpManager.queryQuickBindSwitch(PanelBingingActivity.this, coreId,panelSerialNo, ""+panelIndex,new HttpCallback<HttpData<SwitchBindBean>>(PanelBingingActivity.this) {
            @Override
            public void onSucceed(HttpData<SwitchBindBean> result) {
                super.onSucceed(result);
                if (result.getData() != null) {
                    switch (result.getData().getState()) {
                        case 1://继续轮询等待
                            if(checkCount > 2){
                                operateBindView.endWait();
                                hideDialog();
                                showFailView();
                            }else{
                                checkCount++;
                            }
                            break;
                        case 2://绑定成功
                            editKeyName();
                            //绑定结束
                            break;
                        case 3://绑定失败
                        case 4://绑定超时
                            hideDialog();
                            operateBindView.endWait();
                            showFailView();
                            break;
                        case 5://绑定设备不存在
                            hideDialog();
                            operateBindView.endWait();
                            //showConfirmCancelHintDialog();
                            toast("设备不存在");
                            finish();
                        case 6://覆盖绑定成功
                            operateBindView.endWait();
//                                    operateBindView.coverComplete();
//                                    coverReplace();
//                                    buildUIData(switchBindBeans);
//                                    setResult(RESULT_OK);
                            break;
                        case 7://存在绑定
                            operateBindView.endWait();
//                                    addSwitchBindBean = result.getData();
//                                    operateBindView.hasBind();
//                                    coverDialog.show();
                            break;
                    }
                }
            }

            @Override
            public void onFail(Exception e) {
                if(checkCount > 2){
                    operateBindView.endWait();
//                                        showFailView();
                }else{
                    checkCount++;
                }
            }
        });
    }

    @Override
    protected void initData() {
        //获取通知消息
        selectArea.setText(getString(R.string.unlimited_area) );
    }
    @Override
    public void onClick(View view) {
        if (view == selectArea) {
            showSelectAreaDialog(selectArea);
        }
    }

    AreaSelectDialog selectDialog;
    private void showSelectAreaDialog(View atView) {
        if (selectDialog == null) {
            selectDialog = new AreaSelectDialog(getContext(), AreaSelectDialog.TYPE_PANEL_Binging) {
                @Override
                public void onPanelBingingSave(List<DeviceBean> deviceBeans,List<SceneBean> sceneBeans) {
//                    sceneAdapter.setTotalData(result);
                    if(bingingType == 1){
                        List<DeviceBean> newDeviceBeans = new ArrayList<>();
                        for(DeviceBean deviceBean : deviceBeans){
                            if(deviceBean.getDeviceType().equals("tctdl") || deviceBean.getDeviceType().equals("adjustLight") || deviceBean.getType().equals("curtain")){
                                newDeviceBeans.add(deviceBean);
                            }
                        }
                        deviceBeans = newDeviceBeans;
                    }
                    deviceListFragment.setTotalData(deviceBeans);
                    sceneListFragment.setTotalData(sceneBeans);
                    selectArea.setText(selectDialog.getTitle());
                }
            };
            new XPopup.Builder(getContext())
                    .dismissOnBackPressed(true)
                    .atView(atView)
                    .offsetX(DensityUtils.dip2px(getContext(), 0))
                    .offsetY(-DensityUtils.dip2px(getContext(), 50))
                    .asCustom(selectDialog);
        }
        List<FloorBean> floors = LLFloorDBManager.getInstance(getContext()).getNotEmptyRoomFloors();
        floors.remove(0);
        selectDialog.setFloorBeans(floors);
        selectDialog.show();
    }

    public void showDeviceOperateView(DeviceBean bean){
        if(bingingType == 2 && bingingDatas.size() >= panelIndex){
            return;
        }
        if(bean.getDeviceGroup() == 1){
            operateType = 3;
            bindSerialNo = bean.getDeviceGroupSerialNo();
        }else{
            operateType = 1;
            bindSerialNo = bean.getDeviceSerialNo();
        }
        DeviceBaseConfigInfo deviceBaseConfigInfo = DeviceInfoParseUtil.parseData(getContext(), bean.getDeviceType(), DeviceBaseConfigInfo.class);
        List<DeviceBindingData> mDeviceBingingData = deviceBaseConfigInfo.getBingingData();
        if(bean.getType().equals("universal") || bean.getDeviceType().equals("universal_freshair")){
            List<UniversalDeviceData> datas = LLDeviceActionDBManager.getInstance(this).getEnalbeDeviceDatasByDeviceSerialNo(bean.getDeviceSerialNo());
            mDeviceBingingData = new ArrayList<>();
            DeviceBindingData bindingData = new DeviceBindingData();
            bindingData.setKey("operation");
            bindingData.setName("操作");
            bindingData.setBingingType(0);
            bindingData.setActionType(1);
            List<DeviceBindingData.Data> bingingDatas = new ArrayList<>();
            for(UniversalDeviceData data : datas){
                DeviceBindingData.Data newData = new DeviceBindingData.Data();
                if(bean.getDeviceType().equals("universal_sequencer")){
                    newData.setName(String.format("%s:%s",data.getCombineName(),data.getRangeName()));
                }else{
                    newData.setName(data.getRangeName());
                }
                newData.setValue(Integer.parseInt(data.getRangeIdentifier()));
                newData.setBindActionType(Integer.parseInt(data.getRangeIdentifier()));
                bingingDatas.add(newData);
            }
            bindingData.setData(bingingDatas);
            mDeviceBingingData.add(bindingData);
        }
        operateBindView.setInfoBean(mDeviceBingingData);
        operateBindView.setActionStr(getString(R.string.device_action));
        operateBindView.setVisibility(View.VISIBLE);
        name = bean.getName();
    }

    public void showSceneOperateView(SceneBean bean){
        if(bingingType == 2 && bingingDatas.size() >= panelIndex){
            return;
        }
        if(bingingType == 2 || bingingType == 0){
            operateType = 2;
            bindSerialNo = bean.getSceneSerialNo();
            name = bean.getName();
            panelQRBinging(null,"执行",0,0,0);
        }else{
            List<DeviceBindingData> mDeviceBingingData = new ArrayList<>();
            DeviceBindingData deviceBindingData = new DeviceBindingData();
            deviceBindingData.setName("Binging_Operation");
            List<DeviceBindingData.Data> datas = new ArrayList<>();
            DeviceBindingData.Data data = new DeviceBindingData.Data();
            data.setName("execute");
            datas.add(data);
            deviceBindingData.setData(datas);
            mDeviceBingingData.add(deviceBindingData);
            operateBindView.setInfoBean(mDeviceBingingData);
            operateBindView.setActionStr(getString(R.string.scene_action));
            operateBindView.setVisibility(View.VISIBLE);
            operateType = 2;
            bindSerialNo = bean.getSceneSerialNo();
            name = bean.getName();
        }
    }

    public void removeBingingData(String serialNo,int type){
        for(Map bingingData : bingingDatas){
            if(bingingData.get("bindSerialNo").equals(serialNo)){
                bingingDatas.remove(bingingData);
                break;
            }
        }
    }

    private int checkSame(String bindSerialNo){
        for(int i = 0;i < bingingDatas.size();i++){
            Map bingMap = bingingDatas.get(i);
            if(bindSerialNo.equals(bingMap.get("bindSerialNo"))){
                return i;
            }
        }
        return -1;
    }
    private void showFailView(){
        toast("绑定失败");
    }
}
